package cn.js189.uqc.service.impl;

import cn.js189.common.util.Utils;
import cn.js189.common.util.exception.BSException;
import cn.js189.uqc.transform.IBSResponseTransform;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * bsn费用查询-10113 --> BS:费用查询
 */
@Slf4j
@Component
public class GetAcctItemFqrTransformServiceImpl implements IBSResponseTransform {

	@Override
	public JSONObject transform(String responseString, String tranId) {

		log.debug("费用查询 getAcctItemFQr 开始出参转换");

		try {

			JSONObject resObj = Utils.checkBillResponse(responseString, "errorCode", "errorMsg", "0");

			JSONObject responseBody = new JSONObject();

			JSONObject acctItemFee = resObj.getJSONObject("acctItemFee");

			String chargeCnt = acctItemFee.getString("lTotalCharge");

			// 对应老出参 acctItemFQrlist
			JSONArray acctItemFeeDetail = acctItemFee.getJSONArray("acctItemFeeDetail");

			if (null != acctItemFeeDetail && !acctItemFeeDetail.isEmpty()) {

				JSONArray acctItemFQrlist = new JSONArray();

				for (int i = 0; i < acctItemFeeDetail.size(); i++) {

					// 费用信息明细
					JSONObject detail = acctItemFeeDetail.getJSONObject(i);

					// 费用信息明细转换成老参数
					JSONObject transObj = new JSONObject();
					transObj.put("accNbr", detail.getString("sAccNbr"));
					transObj.put("groupName", detail.getString("sSummaryItemName"));
					transObj.put("dccAcctItemTypeName", detail.getString("sAcctItemTypeName"));
					transObj.put("acctItemTypeId", detail.getString("lAcctItemTypeId"));
					transObj.put("summaryItemId", detail.getString("lSummaryItemID"));
					transObj.put("cycleEndDate", detail.getString("sCycleEndDate"));
					transObj.put("acctItemCharge", detail.getString("lAcctItemCharge"));

					acctItemFQrlist.add(transObj);
				}

				responseBody.put("acctItemFQrlist", acctItemFQrlist);

			}

			responseBody.put("chargeCnt", chargeCnt);
			
			log.debug("费用查询 getAcctItemFQr 出参转换成功");

			return Utils.dealSuccessRespWithBodyAndTranId(tranId, responseBody);

		} catch (BSException e) {
			log.error("费用查询 getAcctItemFQr 参数转换 BSException: {}", e.getErrorMsg());
			return Utils.dealBaseAppExceptionRespNew(tranId, e.getErrorMsg(), e.getErrorCode());
		} catch (Exception e) {
			log.error("费用查询 getAcctItemFQr 参数转换 Exception: {}", e.getMessage());
			return Utils.dealExceptionRespNew(tranId);
		}
	}

}
